package com.authine.cloudpivot.ext.applicationservice;

import com.alibaba.cola.dto.RequestContext;
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.cola.exception.BizException;
import com.alibaba.fastjson.JSON;
import com.authine.cloudpivot.ext.constants.AppConst;
import com.authine.cloudpivot.ext.constants.ErrorCodeConst;
import com.authine.cloudpivot.ext.constants.ModelConst;
import com.authine.cloudpivot.ext.dto.kingDee.request.KingDeeCancelPayment;
import com.authine.cloudpivot.ext.dto.kingDee.request.KingDeePurchaseReceipt;
import com.authine.cloudpivot.ext.dto.kingDee.request.KingDeePurchaseReceiptDetail;
import com.authine.cloudpivot.ext.dto.system.UserDto;
import com.authine.cloudpivot.ext.dto.transfer.TransferConfirmPaymentDto;
import com.authine.cloudpivot.ext.dto.transfer.UpdateConfirmTimeDto;
import com.authine.cloudpivot.ext.enums.order.transfer.InvoiceApplyTypeEnum;
import com.authine.cloudpivot.ext.enums.order.transfer.PurchaseInvoiceEnum;
import com.authine.cloudpivot.ext.service.TransferPurchaseVoucherService;
import com.authine.cloudpivot.ext.utils.BoServiceUtils;
import com.authine.cloudpivot.ext.utils.JdbcTemplateUtils;
import com.authine.cloudpivot.ext.utils.TransferFinanceUtil;
import com.authine.cloudpivot.ext.utils.system.SessionUser;
import com.authine.hermes.app.launcher.service.ApplicationService;
import com.authine.hermes.app.launcher.service.BOService;
import com.authine.mvp.app.launcher.dto.bo.response.BO;
import com.authine.mvp.app.launcher.utils.JsonParseObject;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.authine.hermes.app.launcher.service.ApplicationServiceFoundation.CUSTOM_SERVICE;

/**
 * 转采财务 收票
 *
 * @Author: liwei
 * @DateTime: 2021/8/3
 * @Description: TODO
 */
@Path("TransferFinanceInvoiceController")
@Slf4j
public class TransferFinanceInvoiceController extends ApplicationService {

    List<PurchaseInvoiceEnum> memberPurchaseOrderStatus = Arrays.asList(PurchaseInvoiceEnum.RECEIVED, PurchaseInvoiceEnum.PARTIAL,
            PurchaseInvoiceEnum.CONFIRM, PurchaseInvoiceEnum.SENT, PurchaseInvoiceEnum.FinanceDismissed, PurchaseInvoiceEnum.OrderReceived);

    //金蝶生成凭证服务
    private TransferPurchaseVoucherService transferPurchaseVoucherService = new TransferPurchaseVoucherService();


    @Path("transferConfirmInvoice")
    @POST
    @Operation(summary = "转采财务/采购收票/确认收票", tags = CUSTOM_SERVICE)
    public SingleResponse transferConfirmInvoice(@Parameter TransferConfirmPaymentDto paymentDto) {

        Assert.notNull(paymentDto, "transferConfirmInvoice 入参不能为空 ");
        SessionUser sessionUser = new SessionUser();
        if (null == sessionUser.get()) throw new BizException("未获取到登录信息!");
        //type 2

        //根据收票单 id集合 获取 收票单数据
        List<Map<String, Object>> purchaseInvoices = JdbcTemplateUtils.builder(ModelConst.T_PURCHASE_INVOICE)
                .selectField("*").in("id", paymentDto.getIds()).queryForList();

        Assert.isTrue(null != purchaseInvoices && purchaseInvoices.size() > 0, "未找到收票单数据");

        String companyName = "";
        String vendorOrderId = "";
        String vendorId = "";

        List<KingDeePurchaseReceipt> kingDeePurchaseReceiptList = new ArrayList<>();

        for (Map<String, Object> purchaseInvoice : purchaseInvoices) {

            String invoiceId = String.valueOf(purchaseInvoice.get("id"));
            PurchaseInvoiceEnum purchaseInvoiceStatus = PurchaseInvoiceEnum.get(Integer.valueOf(String.valueOf(purchaseInvoice.get("purchase_invoice_status"))));

            //收票单 状态判断 财务已收票可确认收票， 其他发票状态不可执行确认收票
            if (!purchaseInvoiceStatus.equals(PurchaseInvoiceEnum.SENT)) {
                return SingleResponse.error(ErrorCodeConst.FINANCE_TRANSFER_MANAGEMENT_INVOICE, "收票单 状态不正确 ");
            }

            // 获取收票详情
            List<Map<String, Object>> purchaseInvoiceDetailList = JdbcTemplateUtils.builder(ModelConst.T_PURCHASE_INVOICE_DETAIL)
                    .selectField("*").eq("purchase_invoice_id", invoiceId).queryForList();

            Assert.isTrue(null != purchaseInvoiceDetailList && purchaseInvoiceDetailList.size() > 0, "未获取到 收票单详情 数据");

            //获取 采购收票流水信息 列表
            List<Map<String, Object>> invoiceItemizeList = JdbcTemplateUtils.builder(ModelConst.T_INVOICE_ITEMIZE)
                    .selectField("*").eq("invoice_id", invoiceId).queryForList();

            Assert.isTrue(null != invoiceItemizeList && invoiceItemizeList.size() > 0, "未获取到 采购收票流水 数据");

            //purchase_order_id
            String purchaseOrderId = String.valueOf(purchaseInvoice.get("purchase_order_id"));
            List<String> purchaseOrderIdList = Arrays.asList(purchaseOrderId.split(","));

            //获取 采购订单
            List<Map<String, Object>> memberPurchaseOrderList = JdbcTemplateUtils.builder(ModelConst.T_MEMBER_PURCHASE_ORDER)
                    .selectField("*").in("id", purchaseOrderIdList).queryForList();

            Assert.isTrue(null != memberPurchaseOrderList && memberPurchaseOrderList.size() > 0, "未获取到 会员采购订单数据 数据");

            List<String> vendorOrderIdByCustomerOrderId = new ArrayList<>();

            for (Map<String, Object> memberPurchaseOrder : memberPurchaseOrderList) {

                PurchaseInvoiceEnum memberInvoiceStatus = PurchaseInvoiceEnum.get(Integer.valueOf(String.valueOf(memberPurchaseOrder.get("invoice_status"))));

                if (!memberPurchaseOrderStatus.contains(memberInvoiceStatus)) {
                    return SingleResponse.error(ErrorCodeConst.FINANCE_TRANSFER_MANAGEMENT_INVOICE, "会员采购订单 收票单 状态不正确 ");
                }

                //财务确认收票
                Map<String, Object> memberPurchaseOrderParam = new HashMap<>();
                memberPurchaseOrderParam.put("invoice_status", PurchaseInvoiceEnum.CONFIRM.id);
                memberPurchaseOrderParam.put("id", memberPurchaseOrder.get("id"));

                //更新 会员采购订单表数据
                SingleResponse<BO> memberPurchaseOrderRes = BoServiceUtils.updateMainBo(ModelConst.T_MEMBER_PURCHASE_ORDER, memberPurchaseOrderParam);
                log.info("memberPurchaseOrder:{},memberPurchaseOrderRes:{}",memberPurchaseOrder,memberPurchaseOrderRes.isSuccess());
                Assert.isTrue(memberPurchaseOrderRes.isSuccess(), "会员采购订单表数据 回写状态失败！！！");

                /**    kingdee 收票生成凭证的逻辑     ***/

                //获取 会员采购订单 云平台客户订单id
                String cloudOrderId = String.valueOf(memberPurchaseOrder.get("cloud_order_id"));
                // 获取供应商订单表 id
                List<Map<String, Object>> vendorOrder = JdbcTemplateUtils.builder(AppConst.ORDER_CENTER, ModelConst.T_ORDER_VENDOR)
                        .selectField("*").eq("order_customer_id", cloudOrderId).queryForList();

                // 供应商订单id 列表
                vendorOrderIdByCustomerOrderId = vendorOrder.stream().map(e -> String.valueOf(e.get("id"))).collect(Collectors.toList());

            }

            //获取 会员采购订单  供应商id
            vendorId = String.valueOf(memberPurchaseOrderList.get(0).get("vendor_id"));

            for (Map<String, Object> invoiceItemize : invoiceItemizeList) {


                Map<String, Object> invoiceItemizeParam = new HashMap<>();
                //财务确认
                invoiceItemizeParam.put("financial_confirmation_time", paymentDto.getFinancialConfirmTime());
                invoiceItemizeParam.put("invoice_itemize_status", PurchaseInvoiceEnum.CONFIRM.id);
                invoiceItemizeParam.put("id", invoiceItemize.get("id"));
                //更新 订单收票流水数据
                SingleResponse<BO> invoiceItemizeRes = BoServiceUtils.updateMainBo(ModelConst.T_INVOICE_ITEMIZE, invoiceItemizeParam);
                Assert.isTrue(invoiceItemizeRes.isSuccess(), "订单收票流水数据 回写状态失败！！！");

            }
            Map<String, Object> purchaseInvoiceParam = new HashMap<>();
            purchaseInvoiceParam.put("purchase_invoice_status", PurchaseInvoiceEnum.CONFIRM.id);
            purchaseInvoiceParam.put("financial_confirm_time", paymentDto.getFinancialConfirmTime());
            purchaseInvoiceParam.put("financial_confirmer", sessionUser.getUserFormat());
            purchaseInvoiceParam.put("financial_confirm_name", RequestContext.getLoginName());
            purchaseInvoiceParam.put("id", purchaseInvoice.get("id"));

            vendorOrderId = StringUtils.join(vendorOrderIdByCustomerOrderId, ",");

            List<KingDeePurchaseReceiptDetail> kingDeePurchaseReceiptDetails = new ArrayList<>();

            for (Map<String, Object> purchaseInvoiceDetail : purchaseInvoiceDetailList) {

                Map<String, Object> purchaseInvoiceDetailParam = new HashMap<>();
                purchaseInvoiceDetailParam.put("financial_confirm_time", paymentDto.getFinancialConfirmTime());
                purchaseInvoiceDetailParam.put("purchase_invoice_status", PurchaseInvoiceEnum.CONFIRM.id);
                purchaseInvoiceDetailParam.put("id", purchaseInvoiceDetail.get("id"));

                //更新 收票单详情 数据
                SingleResponse<BO> purchaseInvoiceDetailRes = BoServiceUtils.updateMainBo(ModelConst.T_PURCHASE_INVOICE_DETAIL, purchaseInvoiceDetailParam);
                Assert.isTrue(purchaseInvoiceDetailRes.isSuccess(), "收票单详情 回写状态失败！！！");


                KingDeePurchaseReceiptDetail kingDeePurchaseReceiptDetail = new KingDeePurchaseReceiptDetail();
                String[] poCodeArray = String.valueOf(purchaseInvoiceDetail.get("po_code")).split(",");
                String poCode = null == poCodeArray ? "" : poCodeArray[0];

                kingDeePurchaseReceiptDetail.setPoCode(poCode);
                kingDeePurchaseReceiptDetail.setInvoiceNumber(String.valueOf(purchaseInvoiceDetail.get("invoice_number")));
                kingDeePurchaseReceiptDetail.setInvoicePrice(new BigDecimal(String.valueOf(purchaseInvoiceDetail.get("invoice_price"))));
                kingDeePurchaseReceiptDetail.setPreInvoicePrice(new BigDecimal(String.valueOf(purchaseInvoiceDetail.get("pre_invoice_price"))));
                kingDeePurchaseReceiptDetail.setTaxAmount(new BigDecimal(String.valueOf(purchaseInvoiceDetail.get("tax_amount"))));
                kingDeePurchaseReceiptDetail.setBalanceAmount(purchaseInvoiceDetail.get("balance_amount") == null ? BigDecimal.ZERO : new BigDecimal(String.valueOf(purchaseInvoiceDetail.get("balance_amount"))));
                kingDeePurchaseReceiptDetail.setVendorOrderId(vendorOrderId);

                kingDeePurchaseReceiptDetails.add(kingDeePurchaseReceiptDetail);
            }

            //更新 收票单 数据
            SingleResponse<BO> purchaseInvoiceRes = BoServiceUtils.updateMainBo(ModelConst.T_PURCHASE_INVOICE, purchaseInvoiceParam);
            Assert.isTrue(purchaseInvoiceRes.isSuccess(), "收票单 回写状态失败！！！");

            /**    kingdee 收票生成凭证的逻辑      ***/

            Map<String, BigDecimal> poDetail = new HashMap<>();
            //此处的供应商 id 为 t_transfer_vendor 转采供应商表id，分别对应 京东 & 淘宝 供应商 。因为需要构建金蝶凭证业务逻辑，此处需要写死
            if (vendorId.equals("16") || vendorId.equals("124")) {

                for (Map<String, Object> invoiceItemize : invoiceItemizeList) {
                    //需要根据 流水表对应的订单 获取 po code
                    Map<String, Object> tempOrder = JdbcTemplateUtils.builder(ModelConst.T_MEMBER_PURCHASE_ORDER)
                            .selectField("*").eq("id", String.valueOf(invoiceItemize.get("purchase_id"))).queryForMap();

                    poDetail.put(String.valueOf(tempOrder.get("po_code")), new BigDecimal(String.valueOf(invoiceItemize.get("invoice_amount"))));
                }
            }

            companyName = String.valueOf(purchaseInvoice.get("title")).trim();

            String kingdeeOrgId = TransferFinanceUtil.getKingdeeOrgId(companyName);

            KingDeePurchaseReceipt kingDeePurchaseReceipt = new KingDeePurchaseReceipt();
            kingDeePurchaseReceipt.setId(invoiceId);
            kingDeePurchaseReceipt.setCompanyName(companyName);
            kingDeePurchaseReceipt.setVendorOrgId(kingdeeOrgId);
            kingDeePurchaseReceipt.setInvoiceRate(new BigDecimal(String.valueOf(purchaseInvoice.get("invoice_rate"))));
            kingDeePurchaseReceipt.setInvoiceAmount(new BigDecimal(String.valueOf(purchaseInvoice.get("invoice_amount"))));
            //调整为  采购单未税金额  -> 改为 发票 未税金额
            kingDeePurchaseReceipt.setPreInvoiceAmount(new BigDecimal(String.valueOf(purchaseInvoice.get("pre_invoice_amount"))));

            //订单未税金额
            kingDeePurchaseReceipt.setPreOrderAmount(new BigDecimal(String.valueOf(purchaseInvoice.get("pre_purchase_amount"))));
            kingDeePurchaseReceipt.setInvoiceType(InvoiceApplyTypeEnum.get(Integer.valueOf(String.valueOf(purchaseInvoice.get("invoice_type")))).text);
            kingDeePurchaseReceipt.setFinancialConfirmTime(paymentDto.getFinancialConfirmTime());
            kingDeePurchaseReceipt.setPurchaseInvoiceDetailList(kingDeePurchaseReceiptDetails);
            kingDeePurchaseReceipt.setPoDetail(poDetail);
            kingDeePurchaseReceipt.setAccountName(String.valueOf(purchaseInvoice.get("platform_name")));

            kingDeePurchaseReceiptList.add(kingDeePurchaseReceipt);
        }

        //调用金蝶生成凭证
        transferPurchaseVoucherService.receiptCredentialGeneration(kingDeePurchaseReceiptList);

        log.info("confirmInvoice");
        return null;
    }


    @Path("transferUpdateInvoiceTime")
    @POST
    @Operation(summary = "转采财务/采购收票/修改收票时间", tags = CUSTOM_SERVICE)
    public SingleResponse transferUpdateInvoiceTime(@Parameter UpdateConfirmTimeDto updateConfirmTimeDto) {
        Assert.notNull(updateConfirmTimeDto, "transferUpdateInvoiceTime 入参不能为空 ");


        //根据收票单 id集合 获取 收票单数据
        List<Map<String, Object>> purchaseInvoices = JdbcTemplateUtils.builder(ModelConst.T_PURCHASE_INVOICE)
                .selectField("*").in("id", updateConfirmTimeDto.getIds()).queryForList();

        Assert.isTrue(null != purchaseInvoices && purchaseInvoices.size() > 0, "未找到收票单数据");

        String companyName = "";
        String vendorOrderId = "";
        String vendorId = "";

        for (Map<String, Object> purchaseInvoice : purchaseInvoices) {

            String invoiceId = String.valueOf(purchaseInvoice.get("id"));
            PurchaseInvoiceEnum purchaseInvoiceStatus = PurchaseInvoiceEnum.get(Integer.valueOf(String.valueOf(purchaseInvoice.get("purchase_invoice_status"))));

            //收票单 状态判断  财务确认可修改确认时间，其他发票状态不可执行修改确认时间
            if (!purchaseInvoiceStatus.equals(PurchaseInvoiceEnum.CONFIRM)) {
                return SingleResponse.error(ErrorCodeConst.FINANCE_TRANSFER_MANAGEMENT_INVOICE, "收票单 状态不正确 ");
            }

            // 获取收票详情
            List<Map<String, Object>> purchaseInvoiceDetailList = JdbcTemplateUtils.builder(ModelConst.T_PURCHASE_INVOICE_DETAIL)
                    .selectField("*").eq("purchase_invoice_id", invoiceId).queryForList();

            Assert.isTrue(null != purchaseInvoiceDetailList && purchaseInvoiceDetailList.size() > 0, "未获取到 收票单详情 数据 ");

            //获取 采购收票流水信息 列表
            List<Map<String, Object>> invoiceItemizeList = JdbcTemplateUtils.builder(ModelConst.T_INVOICE_ITEMIZE)
                    .selectField("*").eq("invoice_id", invoiceId).queryForList();

            Assert.isTrue(null != invoiceItemizeList && invoiceItemizeList.size() > 0, "未获取到 采购收票流水 数据 ");

            //purchase_order_id
            String purchaseOrderId = String.valueOf(purchaseInvoice.get("purchase_order_id"));
            List<String> purchaseOrderIdList = Arrays.asList(purchaseOrderId.split(","));

            //获取 采购订单
            List<Map<String, Object>> memberPurchaseOrderList = JdbcTemplateUtils.builder(ModelConst.T_MEMBER_PURCHASE_ORDER)
                    .selectField("*").in("id", purchaseOrderIdList).queryForList();

            Assert.isTrue(null != memberPurchaseOrderList && memberPurchaseOrderList.size() > 0, "未获取到 会员采购订单数据 数据 ");

            List<String> vendorOrderIdByCustomerOrderId = new ArrayList<>();

            for (Map<String, Object> memberPurchaseOrder : memberPurchaseOrderList) {

                PurchaseInvoiceEnum memberInvoiceStatus = PurchaseInvoiceEnum.get(Integer.valueOf(String.valueOf(memberPurchaseOrder.get("invoice_status"))));

                if (!memberPurchaseOrderStatus.contains(memberInvoiceStatus)) {
                    return SingleResponse.error(ErrorCodeConst.FINANCE_TRANSFER_MANAGEMENT_INVOICE, "会员采购订单 收票单 状态不正确 ");
                }

//                //更新 会员采购订单表数据
//                int updateMemberPurchaseOrder = JdbcTemplateUtils.builder(ModelConst.T_MEMBER_PURCHASE_ORDER)
//                        .putFieldAndVal(memberPurchaseOrder).eq("id", String.valueOf(memberPurchaseOrder.get("id"))).update();
//
//                Assert.isTrue(updateMemberPurchaseOrder > 0, "会员采购订单表数据 回写状态失败！！！");

                //获取 会员采购订单 云平台客户订单id
                String cloudOrderId = String.valueOf(memberPurchaseOrder.get("cloud_order_id"));
                // 获取供应商订单表 id
                List<Map<String, Object>> vendorOrder = JdbcTemplateUtils.builder(AppConst.ORDER_CENTER, ModelConst.T_ORDER_VENDOR)
                        .selectField("*").eq("order_customer_id", cloudOrderId).queryForList();

                // 供应商订单id 列表
                vendorOrderIdByCustomerOrderId = vendorOrder.stream().map(e -> String.valueOf(e.get("id"))).collect(Collectors.toList());

            }

            //获取 会员采购订单  供应商id
            vendorId = String.valueOf(memberPurchaseOrderList.get(0).get("vendor_id"));

            Map<String, BigDecimal> poDetail = new HashMap<>();

            for (Map<String, Object> invoiceItemize : invoiceItemizeList) {
                //财务确认
                Map<String, Object> invoiceItemizeParam = new HashMap<>();
                invoiceItemizeParam.put("financial_confirmation_time", updateConfirmTimeDto.getConfirmTime());
                invoiceItemizeParam.put("id", invoiceItemize.get("id"));
                // 更新 订单收票流水数据
                SingleResponse<BO> invoiceItemizeRes = BoServiceUtils.updateMainBo(ModelConst.T_INVOICE_ITEMIZE, invoiceItemizeParam);
                Assert.isTrue(invoiceItemizeRes.isSuccess(), "订单收票流水数据 回写状态失败！！！");

                /***    此处的供应商 id 为 t_transfer_vendor 转采供应商表id，分别对应 京东 & 淘宝 供应商 。因为需要构建金蝶凭证业务逻辑，此处需要写死      ***/
                if (vendorId.equals("16") || vendorId.equals("124")) {

                    //需要根据 流水表对应的订单 获取 po code
                    Map<String, Object> tempOrder = JdbcTemplateUtils.builder(ModelConst.T_MEMBER_PURCHASE_ORDER)
                            .selectField("*").eq("id", String.valueOf(invoiceItemize.get("purchase_id"))).queryForMap();

                    poDetail.put(String.valueOf(tempOrder.get("po_code")), new BigDecimal(String.valueOf(invoiceItemize.get("invoice_amount"))));

                }
            }
            Map<String, Object> purchaseInvoiceParam = new HashMap<>();
            purchaseInvoiceParam.put("financial_confirm_time", updateConfirmTimeDto.getConfirmTime());
            purchaseInvoiceParam.put("id", purchaseInvoice.get("id"));

            vendorOrderId = StringUtils.join(vendorOrderIdByCustomerOrderId, ",");

            List<KingDeePurchaseReceiptDetail> kingDeePurchaseReceiptDetails = new ArrayList<>();

            for (Map<String, Object> purchaseInvoiceDetail : purchaseInvoiceDetailList) {

                Map<String, Object> purchaseInvoiceDetailParam = new HashMap<>();
                purchaseInvoiceDetailParam.put("financial_confirm_time", updateConfirmTimeDto.getConfirmTime());
                purchaseInvoiceDetailParam.put("id", purchaseInvoiceDetail.get("id"));

                // 更新 收票单详情 数据
                SingleResponse<BO> purchaseInvoiceDetailRes = BoServiceUtils.updateMainBo(ModelConst.T_PURCHASE_INVOICE_DETAIL, purchaseInvoiceDetailParam);
                Assert.isTrue(purchaseInvoiceDetailRes.isSuccess(), "收票单详情 回写状态失败！！！");

                KingDeePurchaseReceiptDetail kingDeePurchaseReceiptDetail = new KingDeePurchaseReceiptDetail();

                kingDeePurchaseReceiptDetail.setPoCode(String.valueOf(purchaseInvoiceDetail.get("po_code")));
                kingDeePurchaseReceiptDetail.setInvoiceNumber(String.valueOf(purchaseInvoiceDetail.get("invoice_number")));
                kingDeePurchaseReceiptDetail.setInvoicePrice(new BigDecimal(String.valueOf(purchaseInvoiceDetail.get("invoice_price"))));
                kingDeePurchaseReceiptDetail.setPreInvoicePrice(new BigDecimal(String.valueOf(purchaseInvoiceDetail.get("pre_invoice_price"))));
                kingDeePurchaseReceiptDetail.setTaxAmount(new BigDecimal(String.valueOf(purchaseInvoiceDetail.get("tax_amount"))));
                kingDeePurchaseReceiptDetail.setBalanceAmount(purchaseInvoiceDetail.get("balance_amount") == null ? BigDecimal.ZERO : new BigDecimal(String.valueOf(purchaseInvoiceDetail.get("balance_amount"))));
                kingDeePurchaseReceiptDetail.setVendorOrderId(vendorOrderId);

                kingDeePurchaseReceiptDetails.add(kingDeePurchaseReceiptDetail);
            }

            // 更新 收票单 数据
            SingleResponse<BO> purchaseInvoiceRes = BoServiceUtils.updateMainBo(ModelConst.T_PURCHASE_INVOICE, purchaseInvoiceParam);
            Assert.isTrue(purchaseInvoiceRes.isSuccess(), "收票单 回写状态失败！！！");

            companyName = String.valueOf(purchaseInvoice.get("title")).trim();

            String kingdeeOrgId = TransferFinanceUtil.getKingdeeOrgId(companyName);

            KingDeePurchaseReceipt kingDeePurchaseReceipt = new KingDeePurchaseReceipt();
            kingDeePurchaseReceipt.setId(invoiceId);
            kingDeePurchaseReceipt.setCompanyName(companyName);
            kingDeePurchaseReceipt.setVendorOrgId(kingdeeOrgId);
            kingDeePurchaseReceipt.setInvoiceRate(new BigDecimal(String.valueOf(purchaseInvoice.get("invoice_rate"))));
            kingDeePurchaseReceipt.setInvoiceAmount(new BigDecimal(String.valueOf(purchaseInvoice.get("invoice_amount"))));
            //调整为  采购单未税金额  -> 改为 发票 未税金额
            kingDeePurchaseReceipt.setPreInvoiceAmount(new BigDecimal(String.valueOf(purchaseInvoice.get("pre_invoice_amount"))));

            //订单含税金额
            kingDeePurchaseReceipt.setPreOrderAmount(new BigDecimal(String.valueOf(purchaseInvoice.get("purchase_amount"))));
            kingDeePurchaseReceipt.setInvoiceType(InvoiceApplyTypeEnum.get(Integer.valueOf(String.valueOf(purchaseInvoice.get("invoice_type")))).text);
            kingDeePurchaseReceipt.setFinancialConfirmTime(updateConfirmTimeDto.getConfirmTime());
            kingDeePurchaseReceipt.setPurchaseInvoiceDetailList(kingDeePurchaseReceiptDetails);
            kingDeePurchaseReceipt.setPoDetail(poDetail);
            kingDeePurchaseReceipt.setAccountName(String.valueOf(purchaseInvoice.get("platform_name")));

            //调用金蝶 财务修改收票时间生成凭证
            transferPurchaseVoucherService.modifyTheInvoiceTimeToGenerateTheVoucher(kingDeePurchaseReceipt);

        }

        log.info("updateInvoiceTime");
        return SingleResponse.buildSuccess();
    }


    @Path("transferCancelInvoice")
    @POST
    @Operation(summary = "转采财务/采购收票/取消收票", tags = CUSTOM_SERVICE)
    public SingleResponse transferCancelInvoice(@Parameter List<String> idList) {
        Assert.isTrue(null != idList && idList.size() > 0, "转采财务 采购收票 取消收票 id集合不能为空");

        //type 3

        //根据收票单 id集合 获取 收票单数据
        List<Map<String, Object>> purchaseInvoices = JdbcTemplateUtils.builder(ModelConst.T_PURCHASE_INVOICE)
                .selectField("*").in("id", idList).queryForList();

        Assert.isTrue(null != purchaseInvoices && purchaseInvoices.size() > 0, "未找到收票单数据");

        List<KingDeeCancelPayment> kingDeeCancelPaymentList = new ArrayList<>();

        for (Map<String, Object> purchaseInvoice : purchaseInvoices) {

            String invoiceId = String.valueOf(purchaseInvoice.get("id"));
            PurchaseInvoiceEnum purchaseInvoiceStatus = PurchaseInvoiceEnum.get(Integer.valueOf(String.valueOf(purchaseInvoice.get("purchase_invoice_status"))));

            //收票单 状态判断 财务确认可取消收票，其他发票状态不可执行取消收票
            if (!purchaseInvoiceStatus.equals(PurchaseInvoiceEnum.CONFIRM)) {

                return SingleResponse.error(ErrorCodeConst.FINANCE_TRANSFER_MANAGEMENT_INVOICE, "收票单 状态不正确 ");
            }

            // 获取收票详情
            List<Map<String, Object>> purchaseInvoiceDetailList = JdbcTemplateUtils.builder(ModelConst.T_PURCHASE_INVOICE_DETAIL)
                    .selectField("*").eq("purchase_invoice_id", invoiceId).queryForList();

            Assert.isTrue(null != purchaseInvoiceDetailList && purchaseInvoiceDetailList.size() > 0, "未找到 收票单详情 数据");

            //获取 采购收票流水信息 列表
            List<Map<String, Object>> invoiceItemizeList = JdbcTemplateUtils.builder(ModelConst.T_INVOICE_ITEMIZE)
                    .selectField("*").eq("invoice_id", invoiceId).queryForList();

            Assert.isTrue(null != invoiceItemizeList && invoiceItemizeList.size() > 0, "未找到 采购收票流水 数据");

            //purchase_order_id
            String purchaseOrderId = String.valueOf(purchaseInvoice.get("purchase_order_id"));
            List<String> purchaseOrderIdList = Arrays.asList(purchaseOrderId.split(","));

            //获取 采购订单
            List<Map<String, Object>> memberPurchaseOrderList = JdbcTemplateUtils.builder(ModelConst.T_MEMBER_PURCHASE_ORDER)
                    .selectField("*").in("id", purchaseOrderIdList).queryForList();

            Assert.isTrue(null != memberPurchaseOrderList && memberPurchaseOrderList.size() > 0, "未找到 会员采购订单数据 数据");

            List<Map<String, Object>> memberPurchaseOrderParams = new ArrayList<>();
            for (Map<String, Object> memberPurchaseOrder : memberPurchaseOrderList) {
                PurchaseInvoiceEnum memberInvoiceStatus = PurchaseInvoiceEnum.get(Integer.valueOf(String.valueOf(memberPurchaseOrder.get("invoice_status"))));

                if (!memberPurchaseOrderStatus.contains(memberInvoiceStatus)) {
                    return SingleResponse.error(ErrorCodeConst.FINANCE_TRANSFER_MANAGEMENT_INVOICE, "会员采购订单 收票单 状态不正确 ");
                }

                //财务取消 采购收票状态改为 财务已收票
                Map<String, Object> memberPurchaseOrderParam = new HashMap<>();
                memberPurchaseOrderParam.put("invoice_status", PurchaseInvoiceEnum.SENT.id);
                memberPurchaseOrderParam.put("id", memberPurchaseOrder.get("id"));
                memberPurchaseOrderParams.add(memberPurchaseOrderParam);

            }

            // 更新会员采购订单数据
            SingleResponse<BO> memberPurchaseOrderRes = BoServiceUtils.updateMainBo(ModelConst.T_MEMBER_PURCHASE_ORDER, memberPurchaseOrderParams);
            Assert.isTrue(memberPurchaseOrderRes.isSuccess(), "更新会员采购订单数据 回写状态失败！！！");


            List<Map<String, Object>> invoiceItemizeParams = new ArrayList<>();
            for (Map<String, Object> invoiceItemize : invoiceItemizeList) {

                Map<String, Object> invoiceItemizeParam = new HashMap<>();
                invoiceItemizeParam.put("financial_confirm_time", null);
                invoiceItemizeParam.put("purchase_invoice_status", PurchaseInvoiceEnum.RECEIVED.id);
                invoiceItemizeParam.put("id", invoiceItemize.get("id"));
                invoiceItemizeParams.add(invoiceItemizeParam);

            }
            //更新 收票单流水数据
            SingleResponse<BO> invoiceItemizeRes = BoServiceUtils.updateMainBo(ModelConst.T_INVOICE_ITEMIZE, invoiceItemizeParams);
            Assert.isTrue(invoiceItemizeRes.isSuccess(), "收票单流水数据 回写状态失败！！！");


            List<Map<String, Object>> purchaseInvoiceDetailParams = new ArrayList<>();
            for (Map<String, Object> purchaseInvoiceDetail : purchaseInvoiceDetailList) {

                Map<String, Object> purchaseInvoiceDetailParam = new HashMap<>();
                purchaseInvoiceDetailParam.put("financial_confirm_time", null);
                purchaseInvoiceDetailParam.put("purchase_invoice_status", PurchaseInvoiceEnum.SENT.id);
                purchaseInvoiceDetailParam.put("id", purchaseInvoiceDetail.get("id"));
                purchaseInvoiceDetailParams.add(purchaseInvoiceDetailParam);

            }
            //更新 收票单明细
            SingleResponse<BO> purchaseInvoiceDetailRes = BoServiceUtils.updateMainBo(ModelConst.T_PURCHASE_INVOICE_DETAIL, purchaseInvoiceDetailParams);
            Assert.isTrue(purchaseInvoiceDetailRes.isSuccess(), "收票单明细 回写状态失败！！！");


            Map<String, Object> purchaseInvoiceParam = new HashMap<>();
            purchaseInvoiceParam.put("purchase_invoice_status", PurchaseInvoiceEnum.SENT.id);
            purchaseInvoiceParam.put("financial_confirm_time", null);
            purchaseInvoiceParam.put("financial_confirmer", null);
            purchaseInvoiceParam.put("financial_confirm_name", null);
            purchaseInvoiceParam.put("id", purchaseInvoice.get("id"));

            //更新 收票单
            SingleResponse<BO> memberRes = BoServiceUtils.updateMainBo(ModelConst.T_PURCHASE_INVOICE, purchaseInvoiceParam);

            Assert.isTrue(memberRes.isSuccess(), "收票单 回写状态失败！！！");

            String accountName = String.valueOf(purchaseInvoice.get("platform_name"));

            KingDeeCancelPayment cancelPayment = new KingDeeCancelPayment(invoiceId, accountName);
            kingDeeCancelPaymentList.add(cancelPayment);
        }

        //请求金蝶 取消凭证
        transferPurchaseVoucherService.purchaseCancelBillingDeleteVoucher(kingDeeCancelPaymentList);

        log.info("cancelInvoice");
        return SingleResponse.buildSuccess();
    }


    @Path("transferRejectInvoice")
    @POST
    @Operation(summary = "转采财务/采购收票/驳回", tags = CUSTOM_SERVICE)
    public SingleResponse transferRejectInvoice(@Parameter List<String> idList) {
        Assert.isTrue(null != idList && idList.size() > 0, "转采财务 采购收票 驳回 id集合不能为空");

        //type 5

        //根据收票单 id集合 获取 收票单数据
        List<Map<String, Object>> purchaseInvoices = JdbcTemplateUtils.builder(ModelConst.T_PURCHASE_INVOICE)
                .selectField("*").in("id", idList).queryForList();

        Assert.isTrue(null != purchaseInvoices && purchaseInvoices.size() > 0, "未找到收票单数据");

        List<KingDeeCancelPayment> kingDeeCancelPaymentList = new ArrayList<>();

        for (Map<String, Object> purchaseInvoice : purchaseInvoices) {

            String invoiceId = String.valueOf(purchaseInvoice.get("id"));
            PurchaseInvoiceEnum purchaseInvoiceStatus = PurchaseInvoiceEnum.get(Integer.valueOf(String.valueOf(purchaseInvoice.get("purchase_invoice_status"))));

            //收票单 状态判断 财务已收票可驳回，其他发票状态不可执行驳回
            if (!purchaseInvoiceStatus.equals(PurchaseInvoiceEnum.SENT)) {

                return SingleResponse.error(ErrorCodeConst.FINANCE_TRANSFER_MANAGEMENT_INVOICE, "收票单 状态不正确 ");
            }

            // 获取收票详情
            List<Map<String, Object>> purchaseInvoiceDetailList = JdbcTemplateUtils.builder(ModelConst.T_PURCHASE_INVOICE_DETAIL)
                    .selectField("*").eq("purchase_invoice_id", invoiceId).queryForList();

            Assert.isTrue(null != purchaseInvoiceDetailList && purchaseInvoiceDetailList.size() > 0, "未获取到 收票单详情 数据");

            //获取 采购收票流水信息 列表
            List<Map<String, Object>> invoiceItemizeList = JdbcTemplateUtils.builder(ModelConst.T_INVOICE_ITEMIZE)
                    .selectField("*").eq("invoice_id", invoiceId).queryForList();

            Assert.isTrue(null != invoiceItemizeList && invoiceItemizeList.size() > 0, "未获取到 采购收票流水 数据");

            //purchase_order_id
            String purchaseOrderId = String.valueOf(purchaseInvoice.get("purchase_order_id"));
            List<String> purchaseOrderIdList = Arrays.asList(purchaseOrderId.split(","));

            //获取 采购订单
            List<Map<String, Object>> memberPurchaseOrderList = JdbcTemplateUtils.builder(ModelConst.T_MEMBER_PURCHASE_ORDER)
                    .selectField("*").in("id", purchaseOrderIdList).queryForList();

            Assert.isTrue(null != memberPurchaseOrderList && memberPurchaseOrderList.size() > 0, "未获取到 会员采购订单数据 数据");

            for (Map<String, Object> memberPurchaseOrder : memberPurchaseOrderList) {

                PurchaseInvoiceEnum memberInvoiceStatus = PurchaseInvoiceEnum.get(Integer.valueOf(String.valueOf(memberPurchaseOrder.get("invoice_status"))));

                if (!memberPurchaseOrderStatus.contains(memberInvoiceStatus)) {
                    return SingleResponse.error(ErrorCodeConst.FINANCE_TRANSFER_MANAGEMENT_INVOICE, "会员采购订单 收票单 状态不正确 ");
                }

                //财务取消 采购收票状态改为 财务驳回收票
                Map<String, Object> memberPurchaseOrderParam = new HashMap<>();
                memberPurchaseOrderParam.put("invoice_status", PurchaseInvoiceEnum.FinanceDismissed.id);
                memberPurchaseOrderParam.put("id", memberPurchaseOrder.get("id"));

                SingleResponse<BO> memberPurchaseOrderRes = BoServiceUtils.updateMainBo(ModelConst.T_MEMBER_PURCHASE_ORDER, memberPurchaseOrderParam);
                Assert.isTrue(memberPurchaseOrderRes.isSuccess(), "会员采购订单数据 回写状态失败！！！");

            }

            for (Map<String, Object> purchaseInvoiceDetail : purchaseInvoiceDetailList) {

                Map<String, Object> purchaseInvoiceDetailParam = new HashMap<>();
                purchaseInvoiceDetailParam.put("purchase_invoice_status", PurchaseInvoiceEnum.FinanceDismissed.id);
                purchaseInvoiceDetailParam.put("id", purchaseInvoiceDetail.get("id"));
                //更新 收票单明细
                SingleResponse<BO> purchaseInvoiceDetailRes = BoServiceUtils.updateMainBo(ModelConst.T_PURCHASE_INVOICE_DETAIL, purchaseInvoiceDetailParam);
                Assert.isTrue(purchaseInvoiceDetailRes.isSuccess(), "收票单明细 回写状态失败！！！");

            }

            Map<String, Object> purchaseInvoiceParam = new HashMap<>();
            purchaseInvoiceParam.put("purchase_invoice_status", PurchaseInvoiceEnum.FinanceDismissed.id);
            purchaseInvoiceParam.put("id", purchaseInvoice.get("id"));

            //更新 收票单
            SingleResponse<BO> purchaseInvoiceRes = BoServiceUtils.updateMainBo(ModelConst.T_PURCHASE_INVOICE, purchaseInvoiceParam);
            Assert.isTrue(purchaseInvoiceRes.isSuccess(), "收票单 回写状态失败！！！");

        }

        log.info("rejectInvoice");
        return SingleResponse.buildSuccess();
    }


}
